package dryven.util.crypt;

/** A utility class that takes care of password hashing with salting and key stretching. */
public class PasswordHash {
	
	private String password;
	private String salt;
	private String hash;
	
	/** Use this constructor when checking a password protected entry. The salt needs to be the same as before. */
	public PasswordHash(String password, String salt) {
		super();
		this.password = password;
		this.salt = salt;
	}
	/** Use this constructor when creating a new password protected entry. It generates the salt for you. */
	public PasswordHash(String password) {
		this(password,new RandomAlphaNumericalString(30).generate());
	}

	public String getSalt() {
		return salt;
	}
	
	public String getHash() {
		if(hash==null) {
			hash = calculateHash();
		}
		return hash;
	}

	private String calculateHash() {
		//perform key stretching
		String key = salt+password;
		for(int i=0;i<20000;++i) {
			key = new SHA256Hash(key + password + salt).hash();
		}
		return key;
	}
}
